<template>
  <PageListContainer>
    <div class="base-block">
      <el-button type="primary" class="mb-10" @click="handleOpenDrawer()">新增岗位</el-button>
      <k-table v-bind="tableState" v-on="tableEvent">
        <template #account_count="{ row }">
          <el-link type="primary" @click="handleJump(row)">{{ row.account_count }}</el-link>
        </template>
        <template #is_frozen="{ row }">
          <el-switch
            v-model="row.is_frozen"
            class="ml-2"
            width="40"
            inline-prompt
            :active-value="false"
            :inactive-value="true"
            active-text="开"
            inactive-text="关"
            :before-change="() => handleChangeStatus(row)"
          />
        </template>
        <template #actions="{ row }">
          <el-link type="primary" @click="handleOpenDrawer(row)">编辑</el-link>
          <el-link type="danger" @click="handleRemoveRole(row)">删除</el-link>
        </template>
      </k-table>
    </div>
    <EditDrawer ref="drawerRef" @after-submit="handleAfterSubmit" />
  </PageListContainer>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { baseConfirm, baseAlert } from '@crud/index';
import { ElMessage } from 'element-plus';
import EditDrawer from './components/edit-drawer.vue';
import { removeRole, toggleRoleStatus } from '@/api/crm-kgj/auth';
import { useRouter } from 'vue-router';
import { hasPermission } from '@/modules/auth';
defineOptions({
  name: 'KgjRoleList'
});
const router = useRouter();
import { useTableList } from './hooks/use-table';
const { tableState, tableEvent, ...methods } = useTableList({});
const drawerRef = ref();
/** 切换状态 */
const handleChangeStatus = async (row) => {
  if (hasPermission(610)) {
    await baseConfirm({ title: '关闭岗位', message: '关闭岗位后新增账号时将无法选择该岗位', type: 'error' });
    const { role_id, is_frozen } = row;
    const res = await toggleRoleStatus({ role_id, is_frozen: !is_frozen });
    if (!res.err) {
      methods.onSearch();
    }
  }
  return false;
};
const handleOpenDrawer = (row?) => {
  if (hasPermission(610)) {
    drawerRef?.value.show(row ? 1 : 0, row);
  }
};
const handleRemoveRole = async (row) => {
  if (hasPermission(610)) {
    const { account_count, role_id } = row;
    if (account_count > 1) {
      baseAlert({ title: '错误提示', message: '当前岗位存在多个子账号，无法进行删除', type: 'error' });
      return;
    }
    await baseConfirm({ title: '删除岗位', message: '删除岗位后，将无法再使用该岗位' });
    const res = await removeRole({ role_id });
    if (!res.err) {
      ElMessage.success('删除成功');
      handleAfterSubmit();
    }
  }
};
/** 提交编辑后的回调 */
const handleAfterSubmit = () => {
  methods.onSearch();
};
/** 跳转到账号管理 */
const handleJump = (row) => {
  router.push({ name: 'KgjAccountManage', query: { roleName: row.role_name } });
};
</script>
